package tgeo;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;

public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

	private PrintStream sysOut;
	private PrintStream sysErr;

	public ApplicationWorkbenchWindowAdvisor(
			IWorkbenchWindowConfigurer configurer) {
		super(configurer);
	}

	public ActionBarAdvisor createActionBarAdvisor(
			IActionBarConfigurer configurer) {
		return new ApplicationActionBarAdvisor(configurer);
	}

	public void preWindowOpen() {
		IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
		configurer.setInitialSize(new Point(400, 300));
		configurer.setShowCoolBar(false);
		configurer.setShowStatusLine(false);

		MessageConsole myConsole = new MessageConsole("Console", null, true);
		sysOut = System.out;
		sysErr = System.err;
		MessageConsoleStream newOut = myConsole.newMessageStream();

		newOut.setColor(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));

		MessageConsoleStream newErr = myConsole.newMessageStream();
		newErr.setColor(Display.getCurrent().getSystemColor(SWT.COLOR_RED));

		System.setOut(new PrintStream(new DualOutStream(sysOut, newOut)));
		System.setErr(new PrintStream(new DualOutStream(sysErr, newErr)));

		IConsoleManager consoleManager = ConsolePlugin.getDefault()
				.getConsoleManager();
		consoleManager.addConsoles(new IConsole[] { myConsole });

	}

	@Override
	public void postWindowClose() {
		System.setOut(sysOut);
		System.setErr(sysErr);

		super.postWindowClose();
	}

	private static class DualOutStream extends OutputStream {
		private OutputStream firstOut;
		private OutputStream secondOut;

		public DualOutStream(OutputStream firstOut, OutputStream secondOut) {
			this.firstOut = firstOut;
			this.secondOut = secondOut;
		}

		public void close() {
		}

		public void flush() {
			try {
				firstOut.flush();
				secondOut.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void write(final byte[] b) throws IOException {
			firstOut.write(b);
			secondOut.write(b);
		}

		public void write(final byte[] b, final int off, final int len)
				throws IOException {
			firstOut.write(b, off, len);
			secondOut.write(b, off, len);
		}

		public void write(final int b) throws IOException {
			firstOut.write(b);
			secondOut.write(b);
		}
	}

}
